<?php

declare(strict_types=1);

namespace WebTus;

class TusFileInfo
{
    public const CONCAT_NORMAL = 0; //普通上传
    public const CONCAT_PARTIAL = 1; //部分上传
    public const CONCAT_FINAL = 2; //最终上传

    public $id;
    public $hash;
    public $path = '';
    public $ori;
    public $size = 0;
    public $offset = 0;
    public $checksum; //示例: sha1 Kq5sNclPz7QV2+lfQIuc6R7oRu0=
    public $metadata = []; //array
    public $concat = self::CONCAT_NORMAL;
    public $partial; //array 部分上传列表
    public $ctime;
    public $mtime;
    public $sizeIsDeferred = false;
    public $isTemp = false; //是否是临时文件

    /**
     * TusFileInfo constructor.
     * @param string|null $id
     * @param array|null $items
     */
    public function __construct(string $id = null, array $items = null)
    {
        if (is_array($items)) {
            foreach ($items as $item => $value) {
                $this->$item = $value;
            }
        } else {
            $this->mtime = $this->ctime = time();
        }
        if ($id !== null) {
            $this->id = $id;
        }
    }

    public function __toString()
    {
        return TusService::json($this->toArray(false));
    }

    public function toArray(bool $hasId = true): array
    {
        $info = [
            //"id" => $this->id,
            "path" => $this->path,
            "metadata" => $this->metadata,
            "size" => $this->size,
            "offset" => $this->offset,
            "concat" => $this->concat,
            "ctime" => $this->ctime,
            "mtime" => $this->mtime,
        ];
        if ($hasId) {
            $info['id'] = $this->id;
        }
        if ($this->ori) {
            $info['ori'] = $this->ori;
        }
        if ($this->hash) {
            $info['hash'] = $this->hash;
        }
        if ($this->checksum) {
            $info['checksum'] = $this->checksum;
        }
        if ($this->partial) {
            $info['partial'] = $this->partial;
        }
        if ($this->isTemp) {
            $info['isTemp'] = $this->isTemp;
        }
        if ($this->sizeIsDeferred) {
            $info['sizeIsDeferred'] = $this->sizeIsDeferred;
        }
        return $info;
    }

    public function isFinal(): bool
    {
        return $this->concat === self::CONCAT_FINAL;
    }

    public function isPartial(): bool
    {
        return $this->concat === self::CONCAT_PARTIAL;
    }
}
